package com.business.user.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.business.common.dto.R;
import com.business.common.enums.ErrorEnum;
import com.business.common.utils.FileUploadUtil;
import com.business.redis.ExpiresTimeEnum;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import com.business.user.annotation.TokenPermission;
import com.business.user.entity.UserDetails;
import com.business.user.entity.UserDto;
import com.business.user.service.UserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户详细信息表: 后端controller类
 *
 * @author chenjiehong
 * @date 2019-12-03 10:07:50
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/details")
public class UserDetailsController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 更新基础信息
     *
     * @date 2019-04-28 15:03:18
     */
    @PostMapping("/update")
    @TokenPermission
    public R update(@RequestBody UserDetails userDetails, UserDto user) {
        userDetails.setUserId(user.getId());
        UserDetails r = userDetailsServiceImpl.update(userDetails);
        //删除缓存
        String key = String.format(RedisKeyConstant.USER_DETAILS_QUERY_USER, user.getId());
        RedisUtil.delValue(key);
        String nameKey = String.format(RedisKeyConstant.USER_DETAILS_QUERY_NAME, user.getId());
        RedisUtil.delValue(nameKey);
        return R.success(r);

    }

    /**
     * 获取用户信息
     * 从数据库中读取
     *
     * @date 2019-04-28 15:03:18
     */
    @GetMapping("/getUserInfo")
    @TokenPermission
    public R getUserInfo(UserDto user) {
        return R.success(userDetailsServiceImpl.query(user.getId()));
    }


    /**
     * 获取用户信息
     *
     * @date 2019-04-28 15:03:18
     */
    @PostMapping("/getUserInfoById")
    public R getUserInfoById(@RequestBody JSONObject params) {
        int id = params.getIntValue("id");
        return R.success(userDetailsServiceImpl.query(id));
    }


    @PostMapping("/queryName")
    @ResponseBody
    public R queryName(@RequestBody JSONObject params) {
        int id = params.getIntValue("id");
        String key = String.format(RedisKeyConstant.USER_DETAILS_QUERY_NAME, id);
        if (!RedisUtil.hasKey(key)) {
            Map<String, Object> r = userDetailsServiceImpl.queryName(id);
            RedisUtil.setValue(key, r, ExpiresTimeEnum.LEVEL_12.getExpiresTime());
            return R.success(r);
        } else {
            return R.success(RedisUtil.getObject(key, Map.class));
        }
    }

    @PostMapping("/queryNameList")
    public R queryNameList(@RequestBody JSONObject params) {
        JSONArray jsonArray = params.getJSONArray("ids");
        List<Map<String, Object>> r = userDetailsServiceImpl.queryNameList(jsonArray.toJavaList(Integer.class));
        r.forEach(map -> {
            if (map.get("userId") == null) {
                return;
            }
            Integer id = Integer.parseInt(map.get("userId") + "");
            String key = String.format(RedisKeyConstant.USER_DETAILS_QUERY_NAME, id);
            RedisUtil.setValue(key, map, ExpiresTimeEnum.LEVEL_12.getExpiresTime());
        });
        return R.success(r);
    }

    /**
     * 上传头像 或者 更新头像信息
     *
     * @param fileUpload
     * @date 2019-04-28 15:03:18
     */
    @PostMapping("/updateHeadImage")
    @TokenPermission
    public R updateHeadImage(@RequestPart("file") MultipartFile fileUpload, UserDto user) throws Exception {
        String filUrl = fileUploadUtil.uploadImage(fileUpload);
        try {
            String oldFilePath = userDetailsServiceImpl.updateHeadImage(user.getId(), filUrl);
            //删除旧图片
            fileUploadUtil.delFile(oldFilePath);
            //删除缓存
            String nameKey = String.format(RedisKeyConstant.USER_DETAILS_QUERY_NAME, user.getId());
            String detailsKey = String.format(RedisKeyConstant.USER_DETAILS_QUERY_USER, user.getId());
            Set<String> keys = new HashSet();
            keys.add(nameKey);
            keys.add(detailsKey);
            RedisUtil.delValue(keys);
            return R.success(filUrl);
        } catch (Exception e) {
            logger.error(e.getMessage());
            fileUploadUtil.delFile(filUrl);
        }
        return R.error(ErrorEnum.SERVER_ERROR);

    }


    /**
     * 上传名片 或者 更新名片
     *
     * @param fileUpload
     * @date 2020-02-19
     */
    @PostMapping("/updateCardImage")
    @TokenPermission
    public R updateCardImage(@RequestPart("file") MultipartFile fileUpload, UserDto user) throws Exception {
        String filUrl = fileUploadUtil.uploadImage(fileUpload);
        try {
            String oldFilePath = userDetailsServiceImpl.updateCardUrl(user.getId(), filUrl);
            //删除旧图片
            fileUploadUtil.delFile(oldFilePath);
            //删除缓存
            String detailsKey = String.format(RedisKeyConstant.USER_DETAILS_QUERY_USER, user.getId());
            Set<String> keys = new HashSet();
            keys.add(detailsKey);
            RedisUtil.delValue(keys);

            return R.success(filUrl);
        } catch (Exception e) {
            logger.error(e.getMessage());
            fileUploadUtil.delFile(filUrl);
        }
        return R.error(ErrorEnum.SERVER_ERROR);

    }

}